#include <algorithm>
#include <cstdio>
#include <cstring>
const signed N = 4000505;
int n, m, maxt;
int q[N], f[N], sum[N], cnt[N];
inline int y(int j) { return f[j] + sum[j]; }
inline int x(int i) { return cnt[i]; }
inline int k(int i) { return i; }
int main() {
#ifndef ONLINE_JUDGE
#ifdef LOCAL
  freopen("testdata.in", "r", stdin);
  freopen("testdata.out", "w", stdout);
#endif
#ifndef LOCAL
  freopen("P5017.in", "r", stdin);
  freopen("P5017.out", "w", stdout);
#endif
#endif

  scanf("%d%d", &n, &m);
  int tmp;
  for (int i = 1; i <= n; ++i) {
    scanf("%d", &tmp);
    ++cnt[tmp];
    maxt = std::max(maxt, tmp);
    sum[tmp] += tmp;
  }
  for (int i = 1; i < maxt + m; ++i) {
    sum[i] += sum[i - 1], cnt[i] += cnt[i - 1];
  }
  int l = 1, r = 0;
  memset(f, 0x3f, sizeof(f));
  for (int i = 0; i < maxt + m; ++i) {
    if (i - m >= 0) {
      while (l < r && 1ll * (y(i - m) - y(q[r])) * (x(q[r]) - x(q[r - 1])) <=
                      1ll * (y(q[r]) - y(q[r - 1])) * (x(i - m) - x(q[r])))
        --r;
      q[++r] = i - m;
    }
    while (l < r && 1ll * k(i) * (x(q[l + 1]) - x(q[l])) >= (y(q[l + 1]) - y(q[l]))) ++l;
    f[i] = cnt[i] * i - sum[i];
    if (l <= r)
      f[i] = std::min(f[i], f[q[l]] + (cnt[i] - cnt[q[l]]) * i - sum[i] + sum[q[l]]);
  }
  int ans = 0x3fffffff;
  for (int i = maxt; i < maxt + m; ++i) {
    ans = std::min(ans, f[i]);
  }
  printf("%d", ans);
  return 0;
}